#include "action.h"
#include "object.h"

#include "stdarg.h"

namespace sde {

    ActionList Action::allActions;

    Action::Action(std::string _type, std::string _name, Object* _object) :
        started(false),
        stopped(false),
        initDepend(""),
        archetype(_type),
        type(_type),
        name(_name),
        object(_object) {
//         log("created");
        allActions.push_back(this);
    }
    
    Action::Action(std::string _archetype, std::string _type, std::string _name, Object* _object) :
        started(false),
        stopped(false),
        initDepend(""),
        archetype(_archetype),
        type(_type),
        name(_name),
        object(_object) {
//         log("created");
        allActions.push_back(this);
    }
    
    Action::~Action() {
//         log("destroyed");
        allActions.remove(this);
    }
    
    void Action::log(const char* fmt, ...) {
        va_list args;
        va_start(args, fmt);
        char buffer[1024];
        vsnprintf(buffer,1023,fmt,args);
        object->log("%s: %s", name.c_str(), buffer);
        va_end(args);
    }
    
    void Action::doRun() {
        if (!started) {
            started = true;
//             log("doRun");
            run();
        }
    }
    
    void Action::doStop() {
        if (started && !stopped) {
            stopped = true;
//             log("doStop");
            stop();
        }
    }
    
    ActionList Action::getAllActionsOfArchetype(std::string _archetype) {
        ActionList actions;
        for (ActionList::iterator i = allActions.begin(); i != allActions.end(); ++i)
            if ((*i)->archetype == _archetype)
                actions.push_back(*i);
        return actions;
    }
    
    Action* Action::getFirstActionOfArchetype(std::string _archetype) {
        for (ActionList::iterator i = allActions.begin(); i != allActions.end(); ++i)
            if ((*i)->archetype == _archetype)
                return *i;
        return 0;
    }
}
